package com.ymr.iot.consumer.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class IotAuthenticationUtil {
    private final static Logger logger = LoggerFactory.getLogger(IotAuthenticationUtil.class);

    /**
     * password签名计算方法，请参见文档：AMQP客户端接入说明。
     */
    public static String doSign(String toSignString, String secret, String signMethod) {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);

        Mac mac = null;
        try {
            mac = Mac.getInstance(signMethod);
            mac.init(signingKey);

        } catch (Exception e) {
            // e.printStackTrace();
            logger.error("获取 MAC 实例时出错，原因:[{}]", e);
        }
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }
}
